<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
-->
<template>
  <div class="msg-main" v-loading="mainLoading">
    <!--<div style="background: rgb(0, 115, 231);height: 50px;display: flex;line-height: 50px;">
      <el-popover ref="popover" width="15%" trigger="hover" placement="bottom-start" popper-class="popperOptions">
        <div v-for="(item,index) in modelList" :key="item.modelId" style="z-index: 10">
          <el-button v-if="item.isChoose==true" @click="chooseModel(item,index)"
                     style="width: 100%;border-radius: 0px;border: 0;z-index: 10;background: lightsteelblue">
            {{item.modelName}} &ensp; <i class="el-icon-check"></i>
          </el-button>
          <el-button v-if="item.isChoose==undefined||item.isChoose==false" @click="chooseModel(item,index)"
                     style="width: 100%;border-radius: 0px;border: 0;z-index: 10">
            {{item.modelName}}
          </el-button>
        </div>
        <img slot="reference" src="https://s1.smartalert.online/2023-06-20/54d355ab-7da0-4110-b548-54a21de275de.png"
             width=32 height=32
             style="border-radius: 50%;margin-top:9.5px;margin-left: 70%;cursor: pointer"/>
      </el-popover>
    </div>-->
    <!--<div style="color: #fff;text-align: center;width: 100%;margin-top: -50px;height: 50px;line-height: 46px;background: rgb(0, 115, 231);">-->
    <div style="color: #fff;text-align: center;width: 100%;margin-top: -50px;height: 45px;line-height: 37px;background: rgb(0, 115, 231);">
      <span style="float: left; margin-left: 10px">
        <el-dropdown @command="handleCommand" :placement="placementValue" style="margin-top: 8px;">
          <span class="el-dropdown-link">
            <i class="el-icon-c-scale-to-original" style="font-size: 25px; color: white"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="item.value+'&&'+item.label" v-for="item in modules">{{ item.label }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
      <span style="font-size: 17px; margin-left: -5%" v-if="!tableLoading">{{chatTitle}}</span>
      <span style="font-size: 17px; margin-left: -5%" v-if="tableLoading">正在响应中...</span>
    </div>
    <div style="cursor: pointer; display: flex;align-items: center;
    margin-top: -50px;height: 50px;float: right;padding: 12.5px;">
      <el-tooltip effect="dark" content="全屏"
                  placement="top-start">
        <div style="color: white;cursor: pointer;font-size: 17px;margin-bottom: -2px;" @click="toggleFullScreen" class="el-icon-full-screen"/>
      </el-tooltip>&nbsp;&nbsp;&nbsp;
      <img @click="close()" onmouseover="this.src='https://s1.smartalert.online/2024-04-22/5a5b1837-bba3-48d7-83bb-181045d5b13c.png'"
          onmouseout="this.src='https://s1.smartalert.online/2023-03-14/3ab77c8a-8660-4522-8bab-e6f62bd8ac21.png'"
           src="https://s1.smartalert.online/2023-03-14/3ab77c8a-8660-4522-8bab-e6f62bd8ac21.png"
           width=14 height=14>
    </div>

<!--    <div class="msg-div" :id="'msg-div'+nowStr">
      <div class="el-table__empty-block"><span class="el-table__empty-text">{{openTime}}</span></div>
      <div class="execution" v-for="item in tableData" :key='item.id'>
        <div class="avue-comment" :class="item.type == '2' ? 'avue-comment&#45;&#45;reverse' : ''">
          <div class="avatar-div">
            <img :src="item.type == '2' ? item.headimgUrl : item.headimgUrl" class="avue-comment__avatar"
                 style="height: 35px;width: 35px">
            &lt;!&ndash;<div class="avue-comment__author">{{item.type == '1' ? item.nickName : item.nickName}}</div>&ndash;&gt;
          </div>
          &lt;!&ndash;<div class="avue-comment__main">&ndash;&gt;
          <div class="avue-comment__header" v-if="isHover==true">
            <div class="avue-comment__create_time">{{item.createTime}}</div>
          </div>
          <div class="avue-comment__body" :style="item.type == '1' ? 'background: #eef0f1;' : 'background: #6BED72;'">
            <div v-if="item.repType == 'text' &&item.type==1"
                 style="margin-top: -10px;margin-bottom:-10px;max-width: 100%;">
              <mavon-editor
                :editable="false"
                :ishljs="true"
                :subfield="false"
                :toolbarsFlag="false"
                codeStyle="tomorrow-night-bright"
                defaultOpen="preview"
                v-model="item.repContent"
                style="overflow: auto;height: 100%;"
              />
              <span v-if="isShow&&item.isLast==true" style="border-right: 4px solid black;"></span>
            </div>
            <div v-if="item.repType == 'text' && item.type==2"
                 style="margin-top: -10px;margin-bottom:-10px;max-width: 100%;line-height: 1.5;font-size: 14px">
              {{item.repContent}}
            </div>
            <div v-if="item.repType == 'link'" class="avue-card__detail">
              <el-link type="success" :underline="false" target="_blank" :href="item.repUrl">
                <div class="avue-card__title"><i class="el-icon-link"></i>{{item.repName}}</div>
              </el-link>
              <div class="avue-card__info" style="height: unset">{{item.repDesc}}</div>
            </div>
          </div>
        </div>
        &lt;!&ndash;</div>&ndash;&gt;
      </div>
    </div>-->

<!--    <div style=" background: #ffffff; padding-bottom: 10px;">
      <el-input
        resize="none"
        type="textarea"
        placeholder="发送给 chatgpt"
        @keydown.native="Keydown"
        v-model="objData.repContent"
        name="textarea"
        :autosize="{ minRows: 1, maxRows: 5}"
        style="margin-left: 3%;width:94%; min-height:41px; border-radius: 12px; border: 1px solid #dde0e3; "
        maxlength="180"
      >
      </el-input>
    </div>-->
    <iframe :src="this.value"
            style="width: 100%; height: 90vh;"
            frameborder="0"
            id="myIframe"></iframe>
<!--
    <div style="background: #ffffff; margin-top: -43px; margin-left: 90%">
      <el-image src="https://s1.smartalert.online/2023-04-13/07c4aa1c-2ac3-4fa8-b09c-9f7bb57df745.png"
                style="height: 25px;width: 25px;cursor: pointer;"
                @click="sendMsg"
                v-if="this.objData.repContent==''"
      ></el-image>
      <el-image src="https://s1.smartalert.online/2023-04-13/61471d59-4f3a-4a47-bc65-c20154739420.png"
                style="height: 25px;width: 25px;cursor: pointer;"
                @click="sendMsg"
                v-else
      ></el-image>
    </div>-->
  </div>

</template>

<script>
  import {ajaxGetDictItems, getDictItemsFromCache} from '@/api/api'
  import {mavonEditor} from "mavon-editor";
  import "mavon-editor/dist/css/index.css";

  export default {
    name: "Chatgpt",
    components: {
      mavonEditor
    },
    props: {
      wxUserId: {
        type: String
      },
      chatId: {
        type: Number
      }
    },
    data() {
      return {
        placementValue:'bottom-start',
        isFullScreen: false, // 用于追踪全屏状态
        modules: [],
        value: '',
        visible: false,

        //机器人回复的所有语句的下标
        index: 0,

        chatTitle: 'Powered by LLM',
        LLMname:'',
        GPTname:'',
        modelList: [],
        chooseModelId: '64550bc39c72d6b5e90e50b3',
        chooseModelName: '公共模型',


        isShow: true,
        textCount: 0,
        timer: null,
        timer1: null,

        headimgUrl: '',
        chatgpt_avatar: '',
        chatgpt_fristMsg: '',
        chatgpt_errorMsg: '',
        openTime: '',
        nowStr: new Date().getTime(),
        objData: {
          repType: 'text',
          repContent: ''
        },
        mainLoading: false,
        sendLoading: false,
        tableLoading: false,
        loadMore: true,
        tableData: [],
        options: [],
        optGPT: [],
        dictCode: 'LLM',
        dictGPT: 'GPTServer',
        userId: '',
        avatar: '',
        openId: '',
        nickName: '',
        isHover: false,
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 1, // 每页显示多少条
          ascs: [],//升序字段
          descs: 'create_time'//降序字段
        },
        //查询限制10条
        queryLimit: 10,
        //查询开始下标位
        queryStart: 0,

        option: {
          props: {
            avatar: 'avatar',
            author: 'author',
            body: 'body'
          }
        }
      }
    },
    created() {
      this.getModules()
      console.info("----created----")
      this.openTime = new Date().toLocaleTimeString();
      this.chatgpt_avatar='https://s1.smartalert.online/2023-04-14/1823eda9-5de4-4502-bcfd-81e6f1a234c2.png';
      this.chatgpt_fristMsg='您好,请问有什么我可以帮助您的吗？';
      this.chatgpt_errorMsg='会话已过期,请重新发送您的问题';
      this.refreshChange();
      this.initDict();
      this.initDicts();
      var storedDatas = JSON.parse(localStorage.getItem("pro__Login_Userinfo"));
      // var storedDatass = JSON.parse(localStorage.getItem("Login_Userinfo"));
      console.info("--------storedDatas----------" + JSON.stringify(storedDatas))
      console.info("--------storedDatass----------" + JSON.stringify(storedDatas.value.avatar))
      this.headimgUrl=storedDatas.value.avatar;
     /* this.getDicts("chatgpt_info").then(res => {
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].dictLabel == 'avatar') {
            this.chatgpt_avatar = res.data[i].dictValue;
          } else if (res.data[i].dictLabel == 'fristMsg') {
            this.chatgpt_fristMsg = res.data[i].dictValue;
          } else {
            this.chatgpt_errorMsg = res.data[i].dictValue;
          }
        }
        this.getUser();
        modelList().then(res => {
          if (res.data.items.length > 0) {
            res.data.items[0].isChoose=true;
            this.chatTitle = res.data.items[0].modelName;
            this.chooseModelId = res.data.items[0].modelId
            this.chooseModelName = res.data.items[0].modelName
          }
          this.modelList = res.data.items;
          console.info("--------modelList----------" + JSON.stringify(this.modelList))
        })
      })*/
    },


    destroyed: function () {
      /*this.disconnect()*/
    },
    mounted() {
      /*this.initWebSocket()*/
      window.copy = this.copy
    },
    beforeDestroy() {
      // 页面离开时断开连接,清除定时器
      /*this.disconnect();*/
      clearInterval(this.timer);
    },
    computed: {},
    methods: {

      toggleFullScreen(){
        var iframe=document.getElementById('myIframe')
        iframe.requestFullscreen().catch(err => {
          console.error('Fullscreen request failed:', err);
        });
      },

      toggleFullScreens() {
        if (!this.isFullScreen) {
          // 进入全屏
          const element = document.documentElement;
          if (element.requestFullscreen) {
            element.requestFullscreen();
          } else if (element.mozRequestFullScreen) { // 兼容旧版火狐
            element.mozRequestFullScreen();
          } else if (element.webkitRequestFullscreen) { // 兼容旧版Chrome和Safari
            element.webkitRequestFullscreen();
          } else if (element.msRequestFullscreen) { // 兼容旧版IE
            element.msRequestFullscreen();
          }
          this.isFullScreen = true;
        } else {
          // 退出全屏
          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
          }
          this.isFullScreen = false;
        }
      },

      extractValues(query) {
        // 首先分割字符串，以 '&&' 为分隔符
        const parts = query.split('&&');
        // 检查是否有两个部分
        if (parts.length === 2) {
          // 提取 'Admin-Token=' 到 '&&' 之间的值
          const tokenPart = parts[0];
          // 提取 '&&' 后面的值
          const additionalValue = parts[1];
          return {
            tokenValue: tokenPart,
            additionalValue: additionalValue
          };
        } else {
          // 如果分割后不是两个部分，返回错误信息或 null
          return {
            error: 'Invalid query format'
          };
        }
      },

      handleCommand(command) {
        console.log('========command========'+command);
        const query = command;
        const result = this.extractValues(query);
        if (result.error) {
          console.error(result.error);
        } else {
          console.log("Token Value:", result.tokenValue);
          console.log("Additional Value:", result.additionalValue);
          this.value = result.tokenValue
          console.log('========this.value========='+this.value);
          this.chatTitle=result.additionalValue;
        }
      },

      handleCommands(item) {
        console.log('Selected:', item.label, 'with value:', item.value);
      },
      getModules() {
        this.modules = [];
        //优先从缓存中读取字典配置
        if (getDictItemsFromCache("LLM_UI")) {
          let optIA = getDictItemsFromCache("LLM_UI")
          console.log("modules: " + JSON.stringify(optIA))
          optIA.forEach((item, index) => {
            let person = {};
            person.label = item.title;
            person.value = item.value;
            this.modules.push(person);
            this.chatTitle=this.modules[0].label
            this.value=this.modules[0].value
            console.info("------this.chatTitle------" + this.chatTitle)
          });
          return
        }
      },
      changeModule(){
        console.log("this.value:" + this.value)
      },
      close() {
        this.$emit('child-event', false)
      },


      chooseModel(model, index) {
        console.info("------modelId------" + model.modelId)
        console.info("------modelName------" + model.modelName)
        console.info("------下标------" + index)
        this.chatTitle = model.modelName;
        this.openTime = new Date().toLocaleTimeString();
        this.tableData = [];
        this.refreshChange();
        this.$refs['popover'].doClose();

        var index1 = this.modelList.findIndex(item => item.modelId == this.chooseModelId)
        this.modelList[index1].isChoose = false;

        this.chooseModelId = model.modelId
        this.chooseModelName = model.modelName
        this.modelList[index].isChoose = true;
      },
      /*close() {
        this.$emit('child-event', false)
      },*/
      //实现Enter按钮发送
      Keydown(e) {
        //console.log("--------执行该方法-----------")
        if (e.keyCode == 13) {
          e.cancelBubble = true; //ie阻止冒泡行为
          e.stopPropagation();//Firefox阻止冒泡行为
          e.preventDefault(); //取消事件的默认动作*换行
          //console.info("---------文本内容----------" + this.objData.repContent)
          if (this.objData.repContent != '') {
            this.sendMsg()
          }
        }
      },
      getUser() {
        getUser().then(res => {
          console.info("------res-------" + JSON.stringify(res.data))
          this.userId = res.data.userId;
          this.nickName = res.data.nickName;
          this.avatar = res.data.avatar;
          this.openId = res.data.openId
          this.refreshChange();
        })
      },
      sendMsg() {
        if (this.objData.repContent != '') {
          this.tableLoading = true;
          this.index = this.index + 1;
          this.timer = setInterval(() => {
            this.isShow = !this.isShow;
          }, 300)

          var content = this.objData.repContent;
          this.objData.repContent = '';
          this.tableData.push({
            type: '2',
            headimgUrl:this.headimgUrl,
            repType: 'text',
            repContent: content
          });
          this.tableData.push({
            type: '1',
            headimgUrl: this.chatgpt_avatar,
            repType: 'text',
            repContent: '',
            isLast: true
          });
          this.queryStart++;
          this.scrollToBottom();

         /* if (this.objData.repType == 'news') {
            this.objData.content.articles = [this.objData.content.articles[0]]
            this.$message({
              showClose: true,
              message: '图文消息条数限制在1条以内，已默认发送第一条',
              type: 'success'
            })
          }*/
          this.sendLoading = true;

          //console.log(content)

          let data={
            chatId: this.chatId,
            stream: false,
            detail: false,
            messages: [
              {
                content: content,
                role: 'user'
              }
            ]
          }
          console.log("data:"+JSON.stringify(data))
          console.log("====this.GPTname==="+JSON.stringify(this.GPTname)+"=======this.LLMname======"+JSON.stringify(this.LLMname))
          fetch(this.GPTname, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 'Authorization': 'Bearer fastgpt-5s8pIeOkeOIs1OEl1yrA47vgV3VSpM6jb0U2V8AD6FymLRxJr8XaiZ3vlfWXt1c'
              'Authorization':this.LLMname
            },
            body: JSON.stringify(data)
          })
            .then(response => response.json())
            .then(data => {
              //console.log("进这:"+JSON.stringify(data.choices[0].message.content))
              // 处理响应数据
              this.sendLoading = false;
              var str;
              str = data.choices[0].message.content;

              this.objData = {
                repType: 'text',
                repContent: ''
              }
              this.initGPT(str);
              //console.log("res:"+JSON.stringify(data))
            })
            .catch(error => {
              console.log("返回异常")
              // 处理错误
              var str='接口返回异常';
              this.objData = {
                repType: 'text',
                repContent: ''
              }
              this.initGPT(str);
              this.sendLoading = false
            });
          /*addObj(Object.assign({
            sysUserId: this.userId,
            nickName: this.nickName,
            headimgUrl: this.avatar,
            openId: this.openId,
            repContent: content,
            repType: 'text',
            status: '0',
            modelId: this.chooseModelId,
            modelName: this.chooseModelName
          })).then(data => {
            console.log(JSON.stringify(data))
            this.sendLoading = false;
            var str;
            if (data.msg != '操作成功') {
              str = data.msg;
            } else {
              str = this.chatgpt_errorMsg;
            }
            this.objData = {
              repType: 'text',
              repContent: ''
            }
            this.initGPT(str);
          }).catch(() => {
            this.sendLoading = false
          })*/
        }
      },
      scrollToBottom: function () {
        this.$nextTick(() => {
          let div = document.getElementById('msg-div' + this.nowStr)
          div.scrollTop = div.scrollHeight
        })
      },
      loadingMore() {
        this.queryStart += this.queryLimit;
        //this.page.currentPage++
        this.getPage();
      },
      getPage(params) {
        //console.info("======群聊id===="+this.conversationId)
        //console.info("=======wxId==========="+this.wxUserId)
        this.tableLoading = true
        listMsgById(Object.assign({
          current: this.queryStart,
          size: this.queryLimit,
          //descs: page.descs,
          //ascs: page.ascs,
          //conversationId: this.conversationId,
          wxUserId: this.userId
        }, params)).then(response => {
          let msgDiv = document.getElementById('msg-div' + this.nowStr)
          let scrollHeight = 0
          if (msgDiv) {
            scrollHeight = msgDiv.scrollHeight
          }
          console.info("======data.records=======" + JSON.stringify(response))
          let data = response.data.items/*.records.reverse()*/
          this.tableData = [...data, ...this.tableData]
          //this.page.total = response.data.total
          this.tableLoading = false
          if (data.length < this.queryLimit || data.length == 0) {
            this.loadMore = false
          }
          if (this.queryStart == 0) {//定位到消息底部
            this.scrollToBottom()
          } else {
            if (data.length != 0) {
              this.$nextTick(() => {//定位滚动条
                if (scrollHeight != 0) {
                  msgDiv.scrollTop = document.getElementById('msg-div' + this.nowStr).scrollHeight - scrollHeight - 100
                }
              })
            }
          }
          /*this.page.currentPage = page.currentPage
          this.page.pageSize = page.pageSize*/
        })
        console.info("=====这个方法跑完了======")
      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.tableData.push({
          type: '1',
          headimgUrl: this.chatgpt_avatar,
          nickName: 'chatgpt',
          repType: 'text',
          repContent: this.chatgpt_fristMsg
        });
        this.scrollToBottom();
      },

      initDict() {
        this.options = [];
        //优先从缓存中读取字典配置
        if (getDictItemsFromCache(this.dictCode)) {
          let options = getDictItemsFromCache(this.dictCode)
          options.forEach((item, index) => {
            let person = {};
          person.label = item.title;
          person.value = item.value;
          this.options.push(person);
          // this.chatTitle='Powered by '+this.options[0].label
          this.LLMname=this.options[0].value
        });
          return
        }

        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictCode, null).then((res) => {
          console.log("----字典Code--res----" + JSON.stringify(res));
          if (res.success) {
          let options = res.result
          options.forEach((item, index) => {
            let person = {};
          console.log("----根据字典Code--item----" + JSON.stringify(item))
          person.label = item.title;
          person.value = item.value;
          this.options.push(person);
          console.log("---根据字典Code---this.options-----" + JSON.stringify(this.options))
        });
        }
      })
      },

      initDicts() {
        this.optGPT = [];
        //优先从缓存中读取字典配置
        if (getDictItemsFromCache(this.dictGPT)) {
          let options = getDictItemsFromCache(this.dictGPT)
          options.forEach((item, index) => {
            let persons = {};
          console.log("----根据缓存2--item----" + JSON.stringify(item))
          persons.label = item.title;
          persons.value = item.value;
          this.optGPT.push(persons);
          console.log("----根据缓存2--this.optGPT[0].value----" + JSON.stringify(this.optGPT[0].value))
          this.GPTname=this.optGPT[0].value
        });
          return
        }
        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictGPT, null).then((res) => {
          console.log("----字典Code--res----" + JSON.stringify(res));
        if (res.success) {
          let options = res.result
          options.forEach((item, index) => {
            let persons = {};
          console.log("----根据字典Code2--item----" + JSON.stringify(item))
          persons.label = item.title;
          persons.value = item.value;
          this.GPTname.push(persons);
          console.log("---根据字典Code2---this.GPTname-----" + JSON.stringify(this.GPTname))
        });
        }
      })
      },
      /* // 延时函数
       sleep(delaytime = 10000) {
         return new Promise(resolve => setTimeout(resolve, delaytime));
       },
       // 同步遍历，自定义延时时间
       async delayDo(
         iterList,
         callback = data => console.log(`数据：${data}`),
         delaytimeList
       ) {
         let len = iterList.length;
         for (let i = 0; i < len; i++) {
           callback(iterList[i], i);

           await this.sleep(delaytimeList[i]);
         }
       },
       // 逐字显示内容
       getChatContent(text, index) {
         this.timer = setInterval(() => {
           this.textCount++;

           if (this.textCount == text.length + 1) {
             this.textCount = 0;
             this.chatList.splice(index, 1, { content: text, status: false });
             clearInterval(this.timer);

             return;
           }

           // 取字符串子串
           this.tableData[this.tableData.length-1].repContent = text.substring(0, this.textCount);
         }, 200);
       },*/
      // 点击开始聊天
      initGPT(list) {
        // const delaytimeList = [11000, 8000, 6000, 15000, 4000];
        /* const delaytimeList = [16000, 11000, 16000, 16000, 5000, 7000];

         this.delayDo(
           list,
           (item, i) => {
             this.getChatContent(item, i);
           },
           delaytimeList
         );*/
        clearInterval(this.timer);
        this.isShow=false
        this.timer1 = setInterval(() => {
          this.textCount++;
          if (this.textCount == list.length + 1) {
            this.tableLoading = false
            this.textCount = 0;
            clearInterval(this.timer1);
            this.tableData[this.tableData.length - 1].isLast = false;
            this.addCopyBtn()
            return;
          }
          this.tableData[this.tableData.length - 1].repContent = list.substring(0, this.textCount);
          this.scrollToBottom();
          //this.isShow=!this.isShow;
        }, 40)
      },
      addCopyBtn() {
        this.$nextTick(() => {
          console.info("-------index---------" + this.index)
          const content = document.getElementsByClassName('v-show-content')[this.index]
          //console.info("--------content--------------"+JSON.stringify(content))
          const pres = content.getElementsByTagName('pre')
          //console.info("------pres------------"+JSON.stringify(pres))
          // pres 是个类数组 ，转换一下
          const arr = Array.from(pres)

          arr.forEach((element, index) => {

            const div = content.getElementsByClassName('hljs')[index]

            const btn = document.createElement('div');
            //btn.innerHTML = '复制代码';
            btn.setAttribute("style", 'background: rgb(50, 54, 65);border-top-right-radius: 3px;border-top-left-radius: 3px;color: rgb(255, 255, 255);height: 32px;display: flex')

            var code = undefined;

            if (div != undefined) {
              code = div.children[0]
              var cValue = code.getAttribute("class"); //code标签class值

              console.info("------div------------" + JSON.stringify(cValue))

              const btn1 = document.createElement('div');
              btn1.setAttribute("style", "margin-left: 16px;line-height: 32px;font-size: 90%")
              btn1.innerHTML = cValue.split("-")[1]

              btn.appendChild(btn1)
            } else {
              code = element.children[0] //code标签
              code.setAttribute("style", "color: #eaeaea")
            }

            const codeText = code.innerText

            const btn2 = document.createElement('div');
            btn2.innerHTML = '复制代码'
            btn2.setAttribute("class", "el-icon-copy-document")
            //btn1.setAttribute("class",'code-copy');
            btn2.setAttribute("style", "cursor: pointer;right: 10%;line-height: 32px;position: absolute;font-size: 90%")
            //btn2.setAttribute("onclick","copy("+codeText+")")

            btn2.addEventListener('click', function (e) {
              copy(codeText)
              //this.shareURL('el-icon-copy-document',codeText);
            })


            btn.appendChild(btn2)
            //const btn2 = document.createElement('div');

            element.parentNode.insertBefore(btn, element)
          });
        })
      },
      copy(text) {
        console.info("-------codetext----------" + text)
        // 复制函数
        // 创建一个 textarea标签
        const cInput = document.createElement('textarea')
        cInput.value = text
        document.body.appendChild(cInput)
        cInput.select() // 选取文本域内容;
        // 执行浏览器复制命令
        // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
        // Input要在正常的编辑状态下原生复制方法才会生效
        document.execCommand('Copy')
        this.$message.success("复制成功")
        /// 复制成功后再将构造的标签 移除
        cInput.remove()
      },
    }
  };
</script>
<style>
  .popperOptions {
    width: 15%;
    padding: 0;
    z-index: 9999 !important;
    max-height: 35vh;
    overflow: auto;
  }

  .popperOptions::-webkit-scrollbar {
    display: none;
  }

</style>

<style scoped>
  .msg-main {
    box-shadow: dimgrey 0px 20px 20px 0px;
    background-color: white;
  }

  .msg-div {
    height: 70vh;
    overflow: auto;
    background-color: #f0f2f5;
  }

  .msg-send {
    padding: 10px;
  }

  /*.avue-comment__main {
    flex: unset !important;
    border-radius: 5px !important;
    margin: 0 0px !important;
  }*/

  .avue-comment__header {
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }

  .avue-comment__body {
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    flex: unset !important;
    border-radius: 5px !important;
    margin: 3px -15px !important;
    max-width: 85%;

    padding: 15px;
    overflow: hidden;
    color: #333;
    font-size: 14px;
    font-family:Segoe UI,Lucida Grande,Helvetica,Arial,Microsoft YaHei,FreeSans,Arimo,Droid Sans,wenquanyi micro hei,Hiragino Sans GB,Hiragino Sans GB W3,FontAwesome,sans-serif;
  }

  .avue-comment__avatar{
    border-radius:50%;
    border:1px solid transparent;
    -webkit-box-sizing:border-box;
    box-sizing:border-box;
    vertical-align:middle

  }

  .avatar-div {
    text-align: center;
    width: 80px;
  }

  .avue-comment {
    margin-bottom: 7%;
   /* display: -webkit-box;
    display: -ms-flexbox;*/
    display: flex;
    /*-webkit-box-align: start;
    -ms-flex-align: start;
    align-items: flex-start;*/
  }

  .avue-comment--reverse {
    -webkit-box-orient: horizontal;
    -webkit-box-direction: reverse;
    flex-direction: row-reverse;
  }

  .send-but {
    float: right;
    margin-top: 8px !important;
  }

  ::v-deep .el-textarea__inner {
    outline: none;
    border: none;
    height: 80px;
    border-radius: 0;
    margin-top: 2.9px;
    margin-bottom: 3px;
    margin-left: 3px;
    width: 91%;
    font-size: 14px;
    font-family: 'Open Sans';
    font-weight: initial;
    color: rgb(65, 65, 65);
    border-color: rgb(139, 149, 156);
  }

  .avue-comment__main::before {
    display: none;
  }

  .avue-comment__main::after {
    display: none;
  }

  .el-icon-chat-square::before {
    margin-left: -2px;
  }

  .el-icon-close::before {
    margin-left: -2px;
  }

  ::v-deep .el-input__count {
    margin-right: -20px;
    margin-bottom: -6px;
  }

  ::-webkit-scrollbar {
    display: none;
  }


  ::v-deep .v-show-content {
    background-color: rgb(238, 240, 241) !important;
    padding: 0px;
  }

  ::v-deep pre {
    background-color: black !important;
    border-radius: 0px !important;
    border-bottom-left-radius: 3px !important;
    border-bottom-right-radius: 3px !important;
    font-size: 90% !important;
  }

  ::v-deep .v-note-wrapper {
    box-shadow: 0px 0px !important;
    min-height: 0px;
    min-width: 0px;
  }

  ::v-deep .v-note-wrapper .v-note-panel .v-note-show .v-show-content {
    min-height: 0px;
    min-width: 0px;
    padding: 0px;
  }

  ::v-deep .markdown-body p {
    margin-bottom: 1px;
    font-size: 14px;
  }

  ::v-deep .el-radio-group {
    width: 100%;
  }

  /*::v-deep .el-radio-button__inner{
    width: 100%;
    border-radius: 0px;
    border: 0px;
  }*/
</style>

